package com.yamaha.bikedesalon;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.Gallery;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.FacebookException;
import com.facebook.FacebookOperationCanceledException;
import com.facebook.widget.WebDialog;
import com.facebook.widget.WebDialog.OnCompleteListener;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageLoadingListener;
import com.nostra13.universalimageloader.core.assist.PauseOnScrollListener;
import com.sromku.simple.fb.SimpleFacebook;
import com.sromku.simple.fb.SimpleFacebook.OnLoginListener;
import com.yamaha.bikedesalon.util.API;
import com.yamaha.bikedesalon.util.SCStaticFunc;

public class PostDetailFragment extends AMyActivity {

	private final String TAG = getClass().getSimpleName();
	private final ArrayList<JSONObject> list = new ArrayList<JSONObject>();
	private final MyAdapter adapter = new MyAdapter();
	private JSONObject detail;
	private boolean isMine = false;
	private final List<String> images = new ArrayList<String>();
	private final Map<String, Bitmap> bitmaps = new HashMap<String, Bitmap>();
	private final MyImageAdapter imageAdapter = new MyImageAdapter();

	private final SimpleDateFormat dateTimeFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
	private final SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
	private final SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");

	public PostDetailFragment() {
		super(MenuType.NONE);
	}

	@Override
	protected List<EditText> getEditTexts() {
		return null;
	}

	@Override
	public void onMyClick(View v) {

	}

	@Override
	protected int getLayoutId() {
		return R.layout.post_detail_page;
	}

	@Override
	protected void onMyCreated(final Bundle savedInstanceState) {
		final ListView listView = (ListView) this.findViewById(R.id.post_detail_list);
		listView.setAdapter(this.adapter);

		final boolean pauseOnScroll = true; // or true
		final boolean pauseOnFling = true; // or false
		final PauseOnScrollListener listener = new PauseOnScrollListener(this.imageLoader, pauseOnScroll, pauseOnFling);
		listView.setOnScrollListener(listener);

		final String temp = getIntent().getStringExtra("detail");
		if (temp == null) {
			finish();
			overridePendingTransition(0, 0);
			return;
		} else {
			try {
				LogUtil.d(TAG, temp);
				detail = new JSONObject(temp);
			} catch (JSONException e) {
				LogUtil.e(this, TAG, e.getMessage(), e);
				finish();
				overridePendingTransition(0, 0);
				return;
			}
		}

		// Hide Add Button if it is mine
		try {
			final String userId = detail.getString("user_id");
			if (SCStaticFunc.getUserId(this).equals(userId)) {
				isMine = true;
			}
		} catch (JSONException e) {
			LogUtil.e(TAG, e.getMessage(), e);
		}

		try {
			final JSONArray array = detail.getJSONArray("image");
			for (int i = 0; i < array.length(); i++) {
				images.add(array.getString(i));
			}

			imageAdapter.notifyDataSetChanged();
		} catch (JSONException e) {
			LogUtil.e(TAG, e.getMessage(), e);
		}
	}

	@Override
	protected void onResume() {
		super.onResume();

		getData();
	}

	private void getData() {

		try {
			final AsyncHttpClient client = new AsyncHttpClient();
			final RequestParams params = new RequestParams();
			params.put("item_id", detail.getString("post_id"));
			params.put("user_id", SCStaticFunc.getUserId(this));

			client.post(API.GET_COMMENT, params, new MyAsyncHttpResponseHandler(API.GET_COMMENT, this) {

				@Override
				protected void onAsyncSuccess(final Object res)
						throws JSONException {

					final JSONObject object = (JSONObject) res;

					list.clear();
					final JSONArray items = object.getJSONArray("item");
					for (int i = 0; i < items.length(); i++) {
						list.add(items.getJSONObject(i));
					}

					adapter.notifyDataSetChanged();
				}
			});
		} catch (JSONException e) {
			LogUtil.e(TAG, e.getMessage(), e);
		}
	}

	private class ItemHolder {
		ImageView imageView;
	}

	private class MyImageAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return images.size();
		}

		@Override
		public Object getItem(int position) {
			return images.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			final ItemHolder holder;
			if (convertView == null) {
				holder = new ItemHolder();

				holder.imageView = new ImageView(PostDetailFragment.this);
				holder.imageView.setLayoutParams(new Gallery.LayoutParams(500, 320));
				convertView = holder.imageView;

				convertView.setTag(holder);
			} else {
				holder = (ItemHolder) convertView.getTag();
			}

			holder.imageView.setId(0x55555);
			holder.imageView.setTag(position);
			holder.imageView.setScaleType(ScaleType.CENTER_INSIDE);
			holder.imageView.setPadding(25, 5, 25, 5);
			// holder.imageView.setImageResource(R.drawable.pix_add);
			// holder.imageView.setOnClickListener(this);
			imageLoader.displayImage(images.get(position), holder.imageView, new ImageLoadingListener() {

				@Override
				public void onLoadingStarted(String imageUri, View view) {
					LogUtil.i("BikeDetailFragment", "Load Image Started : " + imageUri);
				}

				@Override
				public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
					LogUtil.w("BikeDetailFragment", "Load Image Failed : " + imageUri);
				}

				@Override
				public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
					bitmaps.put(imageUri, loadedImage);
				}

				@Override
				public void onLoadingCancelled(String imageUri, View view) {
					// TODO Auto-generated method stub

				}
			});

			return convertView;
		}

	}

	private class MyAdapter extends BaseAdapter implements View.OnClickListener {

		@Override
		public int getCount() {
			return 1 + list.size();
		}

		@Override
		public Object getItem(int position) {
			if (position == 0) {
				return null;
			} else {
				return list.get(position - 1);
			}
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (position == 0) {
				convertView = inflater.inflate(R.layout.header_post_detail_item, parent, false);

				try {
					final ImageView postDetailUserImage = (ImageView) convertView.findViewById(R.id.post_detail_user_image);
					imageLoader.displayImage(detail.getString("icon"), postDetailUserImage);
					final TextView postDetailTitle = (TextView) convertView.findViewById(R.id.post_detail_title);
					postDetailTitle.setText(detail.getString("title"));

					final Gallery gallery = (Gallery) convertView.findViewById(R.id.post_detail_images);
					gallery.setAdapter(imageAdapter);

					try {
						final TextView postDetailDate = (TextView) convertView.findViewById(R.id.post_detail_date);
						final TextView postDetailTime = (TextView) convertView.findViewById(R.id.post_detail_time);

						final Date date = Utils.getDate(detail.getLong("last_update"));
						postDetailDate.setText(dateFormat.format(date));
						postDetailTime.setText(timeFormat.format(date));

					} catch (Exception e) {
						LogUtil.e(TAG, e.getMessage(), e);
					}

					final TextView postDetailCode = (TextView) convertView.findViewById(R.id.post_detail_code);
					postDetailCode.setText("Code : " + detail.getString("code"));

					final TextView postDetailCargo = (TextView) convertView.findViewById(R.id.post_detail_cargo);
					postDetailCargo.setText("สินค้า : " + detail.getString("title"));

					final TextView postDetailPrice = (TextView) convertView.findViewById(R.id.post_detail_price);
					postDetailPrice.setText("ราคา : " + detail.getString("price") + " บาท");

					final TextView postDetailDealer = (TextView) convertView.findViewById(R.id.post_detail_dealer);
					postDetailDealer.setText("By : " + detail.getString("dealer_name"));

					final TextView postDetailDetail = (TextView) convertView.findViewById(R.id.post_detail_detail);
					postDetailDetail.setText("Detail : " + detail.getString("description"));

					final ImageButton mailButton = (ImageButton) convertView.findViewById(R.id.post_detail_email_bt);
					final ImageButton commentButton = (ImageButton) convertView.findViewById(R.id.post_detail_comment_bt);
					final ImageButton favButton = (ImageButton) convertView.findViewById(R.id.post_detail_add_bt);
					final ImageButton shareButton = (ImageButton) convertView.findViewById(R.id.post_detail_share_bt);

					mailButton.setOnClickListener(this);
					commentButton.setOnClickListener(this);
					favButton.setOnClickListener(this);
					shareButton.setOnClickListener(this);

					if (detail.getString("user_id").equals(SCStaticFunc.getUserId(PostDetailFragment.this))) {
						favButton.setVisibility(View.GONE);
					} else {
						favButton.setVisibility(View.VISIBLE);
					}

					final boolean isFav = detail.getBoolean("fav");
					if (isFav) {
						favButton.setImageResource(R.drawable.trash);
					} else {
						favButton.setImageResource(R.drawable.post_detail_add);
					}

				} catch (JSONException e) {
					LogUtil.e(TAG, e.getMessage(), e);
				}

			} else {

				convertView = inflater.inflate(R.layout.comment_item, parent, false);
				final ImageView profileImage = (ImageView) convertView.findViewById(R.id.comment_profile);
				final TextView name = (TextView) convertView.findViewById(R.id.c_name);
				final TextView time = (TextView) convertView.findViewById(R.id.c_time);
				final TextView message = (TextView) convertView.findViewById(R.id.c_text);

				try {
					final JSONObject object = list.get(position - 1);
					imageLoader.displayImage(object.getJSONObject("user").getString("profile_image"), profileImage);
					name.setText(object.getJSONObject("user").getString("firstname"));
					final Date date = Utils.getDate(object.getLong("last_update"));
					time.setText(dateTimeFormat.format(date));
					message.setText(object.getString("comment"));
				} catch (JSONException e) {
					LogUtil.e(TAG, e.getMessage(), e);
				}
			}

			return convertView;
		}
		@Override
		public void onClick(final View v) {
			switch (v.getId()) {
				case R.id.post_detail_email_bt : {
					sendMail();
				}
					break;
				case R.id.post_detail_comment_bt : {
					comment();
				}
					break;
				case R.id.post_detail_add_bt : {
					fav();
				}
					break;
				case R.id.post_detail_share_bt : {
					share();
				}
					break;

			}
		}
	}

	private void sendMail() {

		try {
			final Intent i = new Intent(Intent.ACTION_SEND);
			i.setType("message/rfc822");
			i.putExtra(Intent.EXTRA_EMAIL, new String[]{""});
			i.putExtra(Intent.EXTRA_SUBJECT, detail.getString("title"));
			i.putExtra(Intent.EXTRA_TEXT, detail.getString("description"));
			// if (imageFile != null) {
			// i.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(imageFile));
			// }
			try {
				startActivity(Intent.createChooser(i, "Send mail..."));
			} catch (final android.content.ActivityNotFoundException ex) {
				Toast.makeText(PostDetailFragment.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
			}
		} catch (final JSONException e) {
			LogUtil.e(this, TAG, e.getMessage(), e);
		}
	}

	private void fav() {
		try {
			final AsyncHttpClient client = new AsyncHttpClient();
			final RequestParams params = new RequestParams();
			params.put("item_id", detail.getString("post_id"));
			params.put("post_id", detail.getString("post_id"));
			params.put("user_id", SCStaticFunc.getUserId(this));
			LogUtil.v(TAG, "Params : " + params.toString());

			final ProgressDialog progressDialog = Utils.showProgressDialog(this, "", "Please wait...");

			client.post(API.FAVORITE, params, new MyAsyncHttpResponseHandler(API.FAVORITE, this) {

				@Override
				protected void onAsyncSuccess(final Object res)
						throws JSONException {

					final JSONObject obj = (JSONObject) res;
					final String code = obj.getString("code");
					final boolean isDeleted = obj.getBoolean("deleted");
					final boolean isDealer = obj.getBoolean("is_dealer");

					if (isDeleted) {
						detail.put("fav", false);
						detail.put("code", "");
					} else {

						if (isDealer) {
							final AlertDialog.Builder builder = new AlertDialog.Builder(PostDetailFragment.this);
							final View view = inflater.inflate(R.layout.code_layout, null, false);
							final TextView codeView = (TextView) view.findViewById(R.id.code_text);
							codeView.setText(code);
							builder.setMessage(code);
							builder.setPositiveButton("Close", new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog, int which) {
									dialog.dismiss();
								}
							});
							builder.create().show();
						}

						detail.put("fav", true);
						detail.put("code", code);
					}
					adapter.notifyDataSetChanged();
				}

				@Override
				public void onFinish() {
					super.onFinish();

					progressDialog.dismiss();
				}
			});
		} catch (JSONException e) {
			LogUtil.e(this, TAG, e.getMessage(), e);
		}
	}

	private void comment() {
		final Intent intent = new Intent(this, CommentFragment.class);
		intent.putExtra("detail", detail.toString());
		intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
		startActivity(intent);
	}

	private void share() {

		if (simpleFacebook.isLogin()) {
			doShare();
		} else {
			simpleFacebook.login(new OnLoginListener() {

				@Override
				public void onFail(final String reason) {
					Utils.showToast(PostDetailFragment.this, reason);
				}

				@Override
				public void onException(final Throwable throwable) {
					Utils.showToast(PostDetailFragment.this, throwable);
				}

				@Override
				public void onThinking() {

				}

				@Override
				public void onNotAcceptingPermissions() {
					LogUtil.w(TAG, "Facebook Login Not Accepting Permissions");
				}

				@Override
				public void onLogin() {
					doShare();
				}
			});
		}
	}

	private void doShare() {

		try {
			final String description = detail.getString("description");
			final JSONArray images = detail.getJSONArray("image");

			final String picture;
			if (null != images && images.length() > 0) {
				picture = images.getString(0);
			} else {
				picture = "http://ysf.flexintelligent.com/assets/images/pp.jpg";
			}

			final Bundle params = new Bundle();
			params.putString("name", getResources().getString(R.string.app_name));
			params.putString("caption", detail.getString("title"));
			params.putString("description", description.toString());
			params.putString("link", "");
			params.putString("picture", picture);

			LogUtil.v(TAG, "Share Param : " + params.toString());

			final WebDialog feedDialog = (new WebDialog.FeedDialogBuilder(this, SimpleFacebook.getOpenSession(), params)).setOnCompleteListener(new OnCompleteListener() {

				@Override
				public void onComplete(final Bundle values, final FacebookException error) {
					if (error == null) {
						// When the story is posted, echo the success
						// and the post Id.
						final String postId = values.getString("post_id");
						if (postId != null) {
							LogUtil.i(TAG, "Post Success : " + postId);
							Utils.showToast(PostDetailFragment.this, "Post Success");
						} else {
							// User clicked the Cancel button
							LogUtil.i(TAG, "User click Cancel.");
							Utils.showToast(PostDetailFragment.this, "Publish cancelled");
						}
					} else if (error instanceof FacebookOperationCanceledException) {
						// User clicked the "x" button
						LogUtil.i(TAG, "User click Cancel.");
						Utils.showToast(PostDetailFragment.this, "Publish cancelled");
					} else {
						// Generic, ex: network error
						LogUtil.e(TAG, "Facebook Share Error : " + error.getMessage(), error);
						Utils.showToast(PostDetailFragment.this, error.getMessage());
					}
				}

			}).build();
			feedDialog.show();
		} catch (final JSONException e) {
			LogUtil.e(this, TAG, e.getMessage(), e);
		}
	}
}
